#!/bin/bash

IMAGE_NAME="code-generate"
MOJOLICIOUS_TAG="mojolicious"
DATABASE_TAG="database"
SQLITE_TAG="sqlite"
WEBAPP_TAG="webapp"
CONTAINER_NAME="code-generate"

# 自动检测容器引擎
if command -v podman > /dev/null 2>&1; then
    CONTAINER_ENGINE="podman"
elif command -v docker > /dev/null 2>&1; then
    CONTAINER_ENGINE="docker"
else
    echo "Error: Neither 'podman' nor 'docker' is installed." >&2
    exit 1
fi

echo "Using container engine: $CONTAINER_ENGINE"

# 检查 sqlite3 是否已安装
if ! command -v sqlite3 > /dev/null 2>&1; then
    echo "Error: 'sqlite3' is not installed. Please install it to proceed."
    exit 1
fi

# 镜像之间的依赖关系如下:
# perl:latest -> code-generate:mojolicious -> code-generate:database -> code-generate:sqlite -> code-generate:webapp
# 除了 webapp 镜像，其他镜像都可以复用，现在我需要检测这些依赖的镜像是否存在，如果不存在，则创建

DEPENDENCIES=("$MOJOLICIOUS_TAG" "$DATABASE_TAG" "$SQLITE_TAG")

# 检查 perl:latest 是否存在
if ! $CONTAINER_ENGINE images --format "{{.Repository}}:{{.Tag}}" | grep -q "perl:latest$"; then
    echo "Base image 'perl:latest' not found. Please pull or build it first."
    exit 1
fi

# 按顺序检查并构建依赖镜像
for TAG in "${DEPENDENCIES[@]}"; do
    DOCKERFILE="${TAG}.Dockerfile"
    FULL_IMAGE_NAME="${IMAGE_NAME}:${TAG}"

    if ! $CONTAINER_ENGINE images --format "{{.Repository}}:{{.Tag}}" | grep -q "${FULL_IMAGE_NAME}$"; then
        echo "Image '${FULL_IMAGE_NAME}' not found. Building from '${DOCKERFILE}'..."
        $CONTAINER_ENGINE build --tag "${FULL_IMAGE_NAME}" -f "./${DOCKERFILE}" .
    else
        echo "Image '${FULL_IMAGE_NAME}' already exists. Skipping build."
    fi
done

# 检查并删除容器
if $CONTAINER_ENGINE ps -a --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
    echo "Stopping and removing existing container..."
    $CONTAINER_ENGINE stop "$CONTAINER_NAME" > /dev/null 2>&1
    $CONTAINER_ENGINE rm "$CONTAINER_NAME" > /dev/null 2>&1
else
    echo "No existing container named '$CONTAINER_NAME' found."
fi

# 检查并删除镜像
if $CONTAINER_ENGINE images --format "{{.Repository}}:{{.Tag}}" | grep -q "${IMAGE_NAME}:${WEBAPP_TAG}$"; then
    echo "Removing existing image..."
    $CONTAINER_ENGINE rmi "${IMAGE_NAME}:${WEBAPP_TAG}" > /dev/null 2>&1 || true
else
    echo "No existing image named '${IMAGE_NAME}:${WEBAPP_TAG}' found."
fi

# 构建 Docker 镜像
echo "Building image..."
$CONTAINER_ENGINE build --tag "${IMAGE_NAME}:${WEBAPP_TAG}" -f ./webapp.Dockerfile .

# 判断 userdata 目录是否存在，如果不存在则创建，并使用如下命令覆盖内容到 userdata 目录，然后挂载到容器中
# cp ./public/empty-aggregate.puml ./userdata
# cp ./public/demo-aggregate.puml ./userdata
#
# 数据库文件如果存在则跳过，如果不存在则创建
# sqlite3 ./userdata/code-generate.db < ./db/CodeGenerate.sql

# 配置路径
USERDATA_DIR="./userdata"
DB_FILE="$USERDATA_DIR/code-generate.db"
EMPTY_PUML="./src/puml/EmptyAggregate.puml"
DEMO_PUML="./src/puml/DemoAggregate.puml"
INIT_SQL="./src/db/CodeGenerate.sql"

# 创建 userdata 目录（如果不存在）
if [ ! -d "$USERDATA_DIR"  ]; then
    echo "Creating directory: $USERDATA_DIR"
    mkdir -p "$USERDATA_DIR"
fi

# 复制模板文件（如果存在）
if [ -f "$EMPTY_PUML"  ]; then
    cp "$EMPTY_PUML" "$USERDATA_DIR/"
else
    echo "Warning: $EMPTY_PUML not found, skipping copy."
fi

if [ -f "$DEMO_PUML"  ]; then
    cp "$DEMO_PUML" "$USERDATA_DIR/"
else
    echo "Warning: $DEMO_PUML not found, skipping copy."
fi

# 如果数据库文件不存在，则创建并初始化
if [ ! -f "$DB_FILE"  ]; then
    echo "Database file not found. Creating new SQLite database..."
    # 创建空数据库
    sqlite3 "$DB_FILE" "VACUUM;"
    if [ -f "$INIT_SQL"  ]; then
        echo "Initializing database schema..."
        sqlite3 "$DB_FILE" < "$INIT_SQL"
    else
        echo "Warning: $INIT_SQL not found, database created but not initialized."
    fi
else
    echo "Using existing database: $DB_FILE"
fi

# 创建并启动新容器
echo "Creating and starting new container..."
$CONTAINER_ENGINE run --name "$CONTAINER_NAME" \
    -v "$(pwd)/$USERDATA_DIR":/code-generate/userdata \
    -p 3000:3000 \
    -d \
    "${IMAGE_NAME}:${WEBAPP_TAG}"

echo "Deployment completed successfully."
